import React, { useEffect, useRef, useState } from 'react'
import { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Table, message, Radio } from 'antd'
import moment from 'moment'
import SearchForm from '@components/SearchForm/Index'
import CaseNoRender from '@components/CaseNoRender'
import style from '@pages/filingCaseManage/CaseManage.module.less'
import { awaitWrap, formatMoney } from '@js/tool'
import { getData } from './ajax'
import { caseStatusList } from '@js/config'
import Institution from './components/Institution'

// 获取表格字段配置
function getColumns (addWindow) {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '机构',
      dataIndex: 'institution_name',
      key: 'institution_name',
      width: 100
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      width: 150,
      render: (v, l) => {
        return <CaseNoRender data={l} />
      }
    },
    {
      title: '收案时间',
      dataIndex: 'accept_datetime',
      key: 'accept_datetime',
      width: 100,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '立案时间',
      dataIndex: 'docket_datetime',
      key: 'docket_datetime',
      width: 100,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '结案时间',
      dataIndex: 'closure_datetime',
      key: 'closure_datetime',
      width: 100,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '受理费',
      dataIndex: 'fee_acceptance',
      key: 'fee_acceptance',
      width: 100,
      render: v => {
        return formatMoney(v)
      }
    },
    {
      title: '处理费',
      dataIndex: 'fee_processing',
      key: 'fee_processing',
      width: 100,
      render: v => {
        return formatMoney(v)
      }
    },
    {
      title: '仲裁费',
      dataIndex: 'fee',
      key: 'fee',
      width: 100,
      render: v => {
        return formatMoney(v)
      }
    },
    {
      title: '案件状态',
      dataIndex: 'status',
      key: 'status',
      width: 100
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 100,
      fixed: 'right',
      render: (value, line) => {
        return (<span className={style['operate-btn']} onClick={() => openDetail(addWindow, line)}>详情</span>)
      }
    }
  ]
}

// 前往详情
function openDetail (addWindow, data) {
  addWindow({ id: `CaseDetail-${data.id}`, title: `案件详情-${data.caseno_desc || data.acceptno_desc || data.case_no || data.accept_no || data.serial_no}`, componentName: 'CaseDetail', forceRefresh: true, meta: { id: data.id, operate: 'yanchangshenxian' } })
}

const extendParams = [
  { name: 'institution_name', label: '机构', component: Institution, defaultVisible: true }
]

const currentYear = moment().year()
const end = moment(`${currentYear + 1}-01-01 00:00:00`)
end.subtract(1, 'second')

const initialValues = {
  count_inlimit: 0,
  beginTime: moment(`${currentYear}-01-01 00:00:00`),
  endTime: end
}

// 改变分页
function tableChange ({ current, pageSize }, sorter, setCurrent, setPageSize, setOrderField, setOrder) {
  setCurrent(current)
  setPageSize(pageSize)
  setOrderField(sorter.field)
  setOrder(sorter.order)
}

// 获取案件状态
function getStatus (status) {
  if (status === '全部') {
    return { k: 'status', o: 'not in', v: '未提交,待审核,已提交' }
  }
  return { k: 'status', o: '=', v: status }
}

// 获取数据
async function getTableData (condition, current, pageSize, orderField, order, status, setTotal, setList, setLoading) {
  const c = [...condition]
  const s = getStatus(status)
  c.push(s)
  setLoading(true)
  const [e, d] = await awaitWrap(getData(current, pageSize, orderField, order, c))
  setLoading(false)
  if (e) {
    return message.warning(e.message)
  }
  const list = d.list.map((li, i) => {
    li.key = pageSize * (current - 1) + i + 1
    return li
  })
  setList(list)
  setTotal(d.total)
}

// 处理搜索表单扩展字段
function extendCondition (condition, formData) {
  if (formData.institution_name instanceof Array && formData.institution_name.length > 0) {
    condition.push({ k: 'tenant_code', o: 'in', v: formData.institution_name.join(',') })
  }
  return { condition, formData }
}

function Main ({ title, meta, addWindow }) {
  const [ready, setReady] = useState(false)
  const [condition, setCondition] = useState([])
  const [status, setStatus] = useState('全部')
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [orderField, setOrderField] = useState()
  const [order, setOrder] = useState()
  const [pagination, setPagination] = useState({
    current,
    pageSize,
    total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: total => `共 ${total} 条记录`,
    size: 'small'
  })
  const formRef = useRef(null)
  useEffect(() => {
    const c = formRef.current
    // c.showAll()
    c.resetFields()
    c.setFieldsValue(meta ? meta.formData : {})
    setTimeout(() => {
      c.submit()
    }, 0)
  }, [formRef, meta])
  useEffect(() => {
    const p = pagination
    if (p.current !== current || p.pageSize !== pageSize || p.total !== total) {
      setPagination({
        ...p,
        current,
        pageSize,
        total
      })
    }
  }, [current, pageSize, pagination, total])
  useEffect(() => {
    if (ready) {
      getTableData(condition, current, pageSize, orderField, order, status, setTotal, setList, setLoading)
    }
  }, [condition, current, pageSize, ready, orderField, order, status])
  return (
    <div className={style.container}>
      <div className={style['title-line']}>
        <span>{title}</span>
      </div>
      <SearchForm
        ref={formRef} initialValues={initialValues} extendParams={extendParams} extendCondition={(c, f) => extendCondition(c, f)} onChange={d => {
          setCondition(d); setCurrent(1); setReady(true)
        }}
      />
      <div className={style['table-btns-line']}>
        <div className={style['table-tabs-container']}>
          <Radio.Group value={status} onChange={v => setStatus(v.target.value)}>
            <Radio.Button value='全部'>全部</Radio.Button>
            {caseStatusList.map(li => <Radio.Button value={li} key={li}>{li}</Radio.Button>)}
          </Radio.Group>
        </div>
      </div>
      <div className={style['table-container']}>
        <Table loading={loading} columns={getColumns(addWindow)} dataSource={list} pagination={pagination} onChange={(v, filters, sorter) => tableChange(v, sorter, setCurrent, setPageSize, setOrderField, setOrder)} />
      </div>
    </div>
  )
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(Main)
